package com.sychip.fhc.app.wsn.screen

import androidx.activity.compose.LocalActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AccessTime
import androidx.compose.material.icons.outlined.ArrowBackIosNew
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Pause
import androidx.compose.material.icons.outlined.PlayArrow
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fhc.base.EventObserver
import com.fhc.base.LocalManager.stringResource
import com.fhc.base.pxToDp
import com.fhc.view.dialog.FhcConfirmDialog
import com.fhc.view.echarts.EChartsLineScatterWebView
import com.fhc.view.echarts.EChartsType
import com.fhc.view.echarts.EChartsWebView
import com.fhc.view.echarts.initChart
import com.fhc.view.echarts.initChartWith2YData
import com.fhc.view.utils.ToastyShow
import com.sychip.fhc.IS_DEBUG
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.nav.PostToWsnDetail
import com.sychip.fhc.lib.base.FhcTopAppBar


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WsnRssiDetailScreen(
    fromArgument: PostToWsnDetail?,
    onBack:() -> Unit,
    modifier: Modifier = Modifier,
    snackbarHost: SnackbarHostState = remember { SnackbarHostState() },
    viewModel: WsnRssiDetailViewModel = hiltViewModel()
) {
    EventObserver(onResume = {
        viewModel.backToFront()
    }, onPause = {
        viewModel.frontToBack()
    })

    val uiData by viewModel.uiDataState.collectAsStateWithLifecycle()
    if(uiData.toastMsgId != null){
        ToastyShow(msgRes = uiData.toastMsgId!!,uiData.toastMsgArgs, showAfter = {
            viewModel.toastMessageClear()
        })
    }

    val appSettingFlow by viewModel.appSettingFlow.collectAsStateWithLifecycle()
    val restartState by viewModel.restartState.collectAsStateWithLifecycle()
    if(restartState){
        FhcConfirmDialog(appIcon = R.mipmap.ic_launcher,
            title= stringResource(R.string.wsn_q_restart_test_rssi),
            message = stringResource(R.string.wsn_q_restart_test_rssi_msg),
            onPositiveClick = {
                viewModel.startTest()
            },
            onNegativeClick = {viewModel.cancelRestart()}
        )
    }
    Scaffold(
        modifier = modifier.fillMaxSize(),
        snackbarHost = {snackbarHost},
        topBar = { FhcTopAppBar(
            title = uiData.title,
            navigationIcon = {
                IconButton(onClick = onBack) {
                    Icon(Icons.Outlined.ArrowBackIosNew, null)
                }
            },
            actions = {
                if(IS_DEBUG){
                    IconButton(onClick = {
                        viewModel.toggleMockMode()
                    }) {
                        Icon(Icons.Outlined.AccessTime, null)
                    }
                }
                IconButton(onClick = {
//                    viewModel.toImage()
                    viewModel.requestRestart()
                }) {
                    Icon(Icons.Outlined.Delete, null)
                }
            },
        ) }
    ) { innerPadding ->
        Box(modifier = Modifier.padding(top = innerPadding.calculateTopPadding()).fillMaxSize()) {
            DetailContent(
                viewModel = viewModel
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun DetailContent( viewModel: WsnRssiDetailViewModel ) {
    val dateRssiState by viewModel.dateRssiState.collectAsStateWithLifecycle()
    val datePerState by viewModel.datePerState.collectAsStateWithLifecycle()
    val toImageTimeState by viewModel.toImageTimeState.collectAsStateWithLifecycle()
//    val webViewRef = remember { mutableStateOf<WebView?>(null) }
//    LaunchedEffect(webViewRef.value) {
//        withContext(Dispatchers.Main) {
//            if(webViewRef.value != null){
//                initChart(webViewRef.value!!, dateRssiState)
//            }
//        }
//    }

    val context = LocalContext.current
//    Timber.i("   DetailContent   datePerState size >>>>>>>>>>>>>>>>>>>>>>>>>   %s", datePerState.joinToString(","))

    val activity = LocalActivity.current
//    var paddingTop = 0
//    with(LocalDensity.current) {
//        paddingTop = 50.dp.toPx().toInt()
//    }
    var parentSize by remember { mutableStateOf(IntSize.Zero) }
    val scrollState = rememberScrollState()
    val appSettingFlow by viewModel.appSettingFlow.collectAsStateWithLifecycle()
    val perSeconds by viewModel.perSecs.collectAsStateWithLifecycle()
    Column( modifier = Modifier.fillMaxSize().background(colorScheme.secondaryContainer).onGloballyPositioned { layoutCoordinates ->
        parentSize = layoutCoordinates.size
    }
    ) {
        if( parentSize.height  > 0){
            val webViewHeight = parentSize.height.pxToDp() - 100.dp
            Box(modifier = Modifier.padding(20.dp)){
                EChartsLineScatterWebView(
                    context = context,
                    toImageTime = toImageTimeState,
                    onChartImageGenerated = {imgPath ->
                        viewModel.createImageExcel(imgPath)
                        viewModel.sendEmail(activity!!,imgPath)
                    },
                    header = {
                        Row(modifier = Modifier.padding(top = 12.dp, end = 30.dp).fillMaxWidth().wrapContentHeight(),horizontalArrangement = Arrangement.End ){
                            Text(modifier = Modifier.align(alignment=Alignment.CenterVertically).padding(start = 28.dp).wrapContentWidth(),
                                textAlign = TextAlign.Start,
                                color = Color(0xFFF4CB43),
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.Bold,
                                text = stringResource(R.string.wsn_chart_rssi, appSettingFlow.avgNums), maxLines = 1)
                            val  text = buildAnnotatedString {
                                // 添加黑色文本部分
                                append(stringResource(R.string.wsn_rssi_minutes, ""))

                                // 添加红色数字部分
                                withStyle(style = SpanStyle(color = colorScheme.inverseSurface,  fontWeight = FontWeight.Bold)) {
                                    append(appSettingFlow.rssiMins.toString())
                                }
                                append("    ")
                                // 添加黑色文本部分
                                append(stringResource(R.string.wsn_avg_nums, ""))

                                // 添加红色数字部分
                                withStyle(style = SpanStyle(color = colorScheme.inverseSurface,  fontWeight = FontWeight.Bold)) {
                                    append(appSettingFlow.avgNums.toString())
                                }
                            }

                            Text(modifier = Modifier.align(alignment=Alignment.CenterVertically).padding(end = 8.dp).weight(1f),
                                textAlign = TextAlign.End, text = text, maxLines = 1)
//                        FhcSlider(
//                            modifier = Modifier.align(alignment=Alignment.CenterVertically).width(220.dp),
//                            value = avgNum.toFloat(),
//                            steps = 1,
//                            onValueChange = { viewModel.setAvgNum(it.toInt()) },
//                            valueRange = 4f..6f,
//                        )
                        }
                    },
                    onWebPageFinished = { view ->
                        initChartWith2YData(view, dateRssiState)

                    },
                    webViewHeight = webViewHeight/2,
                    chartData = dateRssiState
                )

            }
            Box(modifier = Modifier.padding(start = 20.dp, end = 20.dp)){
                EChartsWebView(
                    context = context,
                    onChartImageGenerated = {imgPath ->
                        viewModel.createImageExcel(imgPath)
                    },
                    header = {
                        Row(modifier = Modifier.padding(top = 12.dp, end = 30.dp).fillMaxWidth().height(IntrinsicSize.Min),horizontalArrangement = Arrangement.End ){
                            Text(modifier = Modifier.align(alignment=Alignment.CenterVertically).padding(start = 28.dp).wrapContentWidth(),
                                textAlign = TextAlign.Start,
                                color = colorScheme.inverseSurface,
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.Bold,
                                text = stringResource(R.string.wsn_chart_per, appSettingFlow.avgNums), maxLines = 1)
                            val  text = if (perSeconds > 0) buildAnnotatedString {
                                val fullText = stringResource(R.string.wsn_per_after_sec, perSeconds.toInt())
                                val targetText = perSeconds.toInt().toString()

                                // 添加黑色文本部分
                                append(fullText.substringBefore(targetText))

                                // 添加红色数字部分
                                withStyle(style = SpanStyle(color = colorScheme.inverseSurface,  fontWeight = FontWeight.Bold)) {
                                    append(targetText)
                                }

                                // 添加剩余黑色文本
                                append(fullText.substringAfter(targetText))
                            } else buildAnnotatedString{}
                            Text(modifier = Modifier.align(alignment=Alignment.CenterVertically).padding(end = 8.dp).weight(1f),
                                textAlign = TextAlign.End, text = text, maxLines = 1)
//                        FhcSlider(
//                            modifier = Modifier.align(alignment=Alignment.CenterVertically).width(220.dp),
//                            value = perSeconds.toFloat(),
//                            steps = 3,
//                            onValueChange = { viewModel.setPerSeconds(it) },
//                            valueRange = 12f..20f,
//                        )
                        }
                    },
                    onWebPageFinished = { view ->
                        initChart(view, datePerState)
                    },
                    webViewHeight = webViewHeight/2,
                    chartData = datePerState,
                    chartType = EChartsType.Scatter
                )

            }

//        ListShimmerView()
//        ListShimmerView()
//            Box(modifier = Modifier.fillMaxWidth().height(80.dp).background(color = Color.Transparent)){}
        }
    }
}


//
//@Preview(showBackground = true)
//@Composable
//fun  NickNameEditContent(title:String = "Title", message:String? = null, @StringRes extraErrMsgId:Int? = null, editValue:String = "",
//                         onValueChange: ((value:String, isError: Boolean) ->Unit) = { _, _ -> } ){
//    var editVal by remember {mutableStateOf(editValue)}
//    var serverErrMsgId by remember { mutableStateOf(extraErrMsgId) }
//    LaunchedEffect(extraErrMsgId) {
//        serverErrMsgId = extraErrMsgId
//    }
//    var isError by remember { mutableStateOf(false) }
//    val errorMessage = if (serverErrMsgId != null) {
//        stringResource(id = serverErrMsgId!!)
//    } else {
//        "请输入6-12位字母或数字"
//    }
//
//    isError = serverErrMsgId != null || !editVal.matches(Regex("^[a-zA-Z0-9]{6,12}$"))
//
//    Column{
//        Row(modifier = Modifier.fillMaxWidth().padding(0.dp),
//            horizontalArrangement = Arrangement.SpaceBetween, // 水平两端对齐
//            verticalAlignment = Alignment.CenterVertically    ){
//            Row(verticalAlignment = Alignment.CenterVertically ) {
//                Box(
//                    modifier = Modifier.size(50.dp) // 固定正方形尺寸
//                        .background(
//                            color = Color.LightGray.copy(alpha = 0.1f), // 可选背景色
//                            shape = RoundedCornerShape(12.dp) // 圆角矩形
//                        ).clip(RoundedCornerShape(12.dp)) ){
//                    Icon(
//                        painter = painterResource(id = com.fhc.view.R.drawable.github), // 加载应用图标R.mipmap.ic_launcher
//                        contentDescription = null,
//                        modifier = Modifier.size(50.dp).padding(4.dp),
//                        tint = Color.Unspecified // 保留图标原始颜色
//                    )
//                }
//                Text( modifier = Modifier.padding(start = 10.dp),text = title.uppercase(),style = TextStyle(
//                    fontSize = 18.sp,
//                    fontFamily = FontFamily.SansSerif,
//                    fontWeight = FontWeight.Bold
//                ) )
//            }
//        }
//        if(message != null){
//        Row( modifier = Modifier.padding(start = 60.dp),verticalAlignment = Alignment.CenterVertically ) {
//            Text(
//                message, style = TextStyle(
//                    fontSize = 16.sp,
//                    fontFamily = FontFamily.SansSerif,
//                    fontWeight = FontWeight.Normal
//                )
//            )
//        }}
//        Row( modifier = Modifier.padding(start = 60.dp, top = 10.dp),verticalAlignment = Alignment.CenterVertically ) {
//            val borderColor = colorResource(id = android.R.color.darker_gray)
//            val errorColor = colorScheme.error
//
//            OutlinedTextField(
//                value = editVal,
//                onValueChange = {
//                    editVal = it.take(10)
//                    onValueChange( editVal, !editVal.matches(Regex("^[a-zA-Z0-9]{6,12}$")))
//                },
//                label = {
//                    Text("用户名", color = if (isError) errorColor else borderColor)
//                },
//                isError = isError,
//                supportingText = {
//                    if (isError) {
//                        Text(text = errorMessage, color = colorScheme.error)
//                    }
//                },
//                trailingIcon = {
//                    if (isError) {
//                        Icon(
//                            Icons.Filled.Error,
//                            "error",
//                            tint = colorScheme.error
//                        )
//                    }
//                },
//                singleLine = true,
//                modifier = Modifier.fillMaxWidth(),
//                shape = MaterialTheme.shapes.medium,
//                colors = OutlinedTextFieldDefaults.colors(
//                    unfocusedContainerColor = Color.Transparent,
//                    focusedContainerColor = Color.Transparent,
//                    errorContainerColor = Color.Transparent,
//                    focusedBorderColor = if (isError) errorColor else borderColor,
//                    unfocusedBorderColor = if (isError) errorColor else borderColor,
//                    errorBorderColor = errorColor,
//                    disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
//                    cursorColor = if (isError) errorColor else colorScheme.primary
//                )
//            )
//        }
//    }
//}
